package com.zjj.distributed.zk.application.idMaker;

import com.zjj.distributed.zk.curator.CuratorBaseOperations;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.junit.Test;

/**
 * @author zhanglei.zjj
 * @description 使用zookeeper实现分布式ID生成器
 * @date 2023/6/20 22:20
 */
@Slf4j
public class ZkIdMaker extends CuratorBaseOperations {
    private String createSeqNode(String pathPefix) throws Exception {

        //创建一个临时顺序节点
        String destPath = curatorFramework.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .forPath(pathPefix);
        return destPath;
    }

    public String makeId(String path) throws Exception {
        String str = createSeqNode(path);
        if (null != str) {
            //获取末尾的序号
            int index = str.lastIndexOf(path);
            if (index >= 0) {
                index += path.length();
                return index <= str.length() ? str.substring(index) : "";
            }
        }
        return str;
    }

    @Test
    public void testMarkId() throws Exception {
        ZkIdMaker idMaker = new ZkIdMaker();
        String pathPrefix = "/idmarker/id-";

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                for (int j = 0; j < 10; j++) {
                    String id = null;
                    try {
                        id = idMaker.makeId(pathPrefix);
                        log.info("{}线程第{}个创建的id为{}", Thread.currentThread().getName(),
                                j, id);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, "thread" + i).start();
        }

        Thread.sleep(Integer.MAX_VALUE);
    }
}
